<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.20.1/ol.css" type="text/css">

<table width=100%><tr><td>区域选择地图弹出 <span style="margin-left: 50px; font-weight: bold;">{{ g.filtertxt }}</span>
        </td><td align='right'><button type="button" class="btn btn-default btn-sm"  onclick="$('#PopupDetails').modal('hide');">关闭</button>&nbsp;&nbsp;
        </td></tr></table>

<div id="map" class="map" style="width: 100%; height: 500px;">
  Displaying Map requires Internet Access to load map from https://server.arcgisonline.com
</div>
<p>拖动鼠标，用Shift+拖动进行缩放，用Alt+拖动进行矩形选择</p>

<table><tr>
  <td>
<table class="table table-condensed" style="width:300px;">
  <tr><td colspan="2" align="Center">北 <input type="text" size="7" id="MapOutN"></td></tr>
  <tr>
    <td>西 <input type="text" size="7" id="MapOutW"></td>
    <td>东 <input type="text" size="7" id="MapOutE"></td></tr>
  <tr><td colspan="2" align="Center">南 <input type="text" size="7" id="MapOutS"></td></tr>
</table>
    </td><td style="vertical-align: middle">
<button type="button" class="btn btn-primary" onClick="DrawInputOnMap();">在地图上绘制</button> <br><br>
<button type="button" class="btn btn-success" onClick="ReturnMapArea();">返回到这个区域</button>
  </td>

</tr></table>
<div id='MapPopup'></div>
<style>
  #map .popover{max-width: 380px; }
</style>
<script>

var map,vectorSource,SampleSource,MapPopupContent;

function InitMap() {
var attribution = new ol.Attribution({
        html: 'Tiles © <a href="https://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer">ArcGIS</a>'
      });

var mousePositionControl = new ol.control.MousePosition({
  coordinateFormat: ol.coordinate.createStringXY(4),
  projection: 'EPSG:4326',
  undefinedHTML: '&nbsp;'
});
$("#map").css('height',$(window).height()-250).html(""); {# Optimise la surface de la carte en fonction de la hauteur de l'écran #}
map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.XYZ({
              attributions: [attribution],
              url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}'
            })
    })
  ],
  controls: ol.control.defaults({
    attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
      collapsible: false
    })
  }).extend([mousePositionControl]),
  target: 'map',
  view: new ol.View({
    center: [0, 47],
    zoom: parseFloat($("#map").css('height'))/450 {# Mise à l'echelle, affiche toute la hauteur à l'echelle 1 sur une zone de 450px de haut #}
  })
});


// a DragBox interaction used to select features by drawing boxes
var dragBox = new ol.interaction.DragBox({
  condition: ol.events.condition.altKeyOnly,
  style: new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: [0, 0, 255, 1]
    })
  })
});

map.addInteraction(dragBox);

var infoBox = document.getElementById('info');

dragBox.on('boxend', function(e) {
  // features that intersect the box are added to the collection of
  // selected features, and their names are displayed in the "info"
  // div
  var info = [];
  var extent = dragBox.getGeometry().getExtent();
  var s=extent+" / ";
  // Calcule les tableau sous forme X/Longitude , Y/Lattitude
  bottomleft= ol.proj.transform([extent[0], extent[1]], 'EPSG:3857', 'EPSG:4326') ;
  topright= ol.proj.transform([extent[2], extent[3]], 'EPSG:3857', 'EPSG:4326') ;
  if((bottomleft[0]<-180)||(bottomleft[0]>180))
      bottomleft[0]=(bottomleft[0]+180)%360-180;
  if((topright[0]<-180)||(topright[0]>180))
      topright[0]=(topright[0]+180)%360-180;
  if(topright[0]<-180) topright[0]+=360;
  $("#MapOutN").val(topright[1].toFixed(4));
  $("#MapOutW").val(bottomleft[0].toFixed(4));
  $("#MapOutE").val(topright[0].toFixed(4));
  $("#MapOutS").val(bottomleft[1].toFixed(4));
  DrawInputOnMap();
{#  console.log(extent);#}
});

// Create vector source and the feature to it.
vectorSource = new ol.source.Vector();
var vectorLayer= new ol.layer.Vector({
  source: vectorSource
});

var RedIconStyle = new ol.style.Style({
        image: new ol.style.Icon({
          anchor: [0.5, 0.5],
          size: [40, 40],
          offset: [52, 0],
          opacity: 1,
          scale: 0.19,
          src: '/static/dots.png'
        })
      });

SampleSource = new ol.source.Vector();
var SampleLayer= new ol.layer.Vector({
  source:SampleSource,style: RedIconStyle
});
// Add the vector layer to the map.
map.addLayer(vectorLayer);
map.addLayer(SampleLayer);

var MapPopupElt = document.getElementById('MapPopup');
var popup = new ol.Overlay({
  element: MapPopupElt,
  positioning: 'bottom-center',
  stopEvent: false,
  offset: [3, 0]
});
map.addOverlay(popup);
// display popup on click
map.on('click', function(evt) {
  var feature = map.forEachFeatureAtPixel(evt.pixel,
      function(feature) {
        return feature;
      });

  if (feature) {
    var coordinates = feature.getGeometry().getCoordinates();
{#    popup.setPosition(coordinates); Utilisation de l'evt plutot pour traiter le monde cyclique#}
    popup.setPosition(evt.coordinate);
{#    console.log(coordinates,evt.coordinate);#}
    MapPopupContent='Get Data for sample '+feature.get('sampleid');
    $(MapPopupElt).popover({
      'placement': 'right',
      'html': true,
      'content': function (){return MapPopupContent;}
    });
    $(MapPopupElt).popover('show');
    $.get('/search/mappopup/getsamplepopover/'+feature.get('sampleid'),function(data){
      MapPopupContent=data;
      $(MapPopupElt).popover('show');
    });
  }
  else
    $(MapPopupElt).popover('destroy');
});

} //InitMap

function DrawSelectionRectangle(a){ {# X Y X Y  #}
  var ring = [ [a[0], a[1]], [a[2], a[1]],  [a[2], a[3]], [a[0], a[3]] , [a[0], a[1]] ];
  var polygon = new ol.geom.Polygon([ring]);
  polygon.transform('EPSG:4326', 'EPSG:3857');
  // Create feature with polygon.
  var feature = new ol.Feature(polygon);
  vectorSource.clear();
  vectorSource.addFeature(feature);
}

function DrawInputOnMap()
{
DrawSelectionRectangle([
    parseFloat($("#MapOutW").val()),
    parseFloat($("#MapOutN").val()),
    parseFloat($("#MapOutE").val()),
    parseFloat($("#MapOutS").val()) ]);
}

 $.getScript("https://cdnjs.cloudflare.com/ajax/libs/ol3/3.20.1/ol.js", function(){
  InitMap();
  $("#MapOutW").val($("#filt_MapOutW").val());
  $("#MapOutN").val($("#filt_MapOutN").val());
  $("#MapOutE").val($("#filt_MapOutE").val());
  $("#MapOutS").val($("#filt_MapOutS").val());
  DrawInputOnMap();
  ShowSample({a:0 {% if g.Projid %} ,projid:"{{g.Projid }}" {%endif%}  {% if g.taxoid %} ,taxoid:"{{g.taxoid }}" {%endif%}  {% if g.taxochild %} ,taxochild:"{{g.taxochild }}" {%endif%}  });
 });

function ReturnMapArea() {
    $("#filt_MapOutW").val($("#MapOutW").val());
    $("#filt_MapOutN").val($("#MapOutN").val());
    $("#filt_MapOutE").val($("#MapOutE").val());
    $("#filt_MapOutS").val($("#MapOutS").val());
    $('#PopupDetails').modal('hide');
}

function ShowSample(p){
{#  console.log(p);#}
$.getJSON( "/search/mappopup/samples/",p, function( data ) {
  SampleSource.clear();
  $.each( data, function( key, val ) {
{#    console.log(key,val);#}
    var iconFeature = new ol.Feature({ geometry: new ol.geom.Point(ol.proj.transform([val['long'],val['lat']], 'EPSG:4326','EPSG:3857'))
        ,sampleid:val['id'] });
    SampleSource.addFeature(iconFeature);

  });

});
}


</script>
